package geppetto.phraseProbability.smoothing;

import geppetto.phraseTable.PhraseTable;
import geppetto.phraseTable.phrase.Phrase;

public class ModifiedKneserNeyDiscount implements DiscountFunction{
	
	boolean initialized = false;
	double Y;
	double D1;
	double D2;
	double D3orMore;

	public double getDiscount(PhraseTable phraseTable, Phrase p) {
		if(!initialized){
			initialize(phraseTable);
		}
		if(p.getCounts() < 2){
			return D1;
		}
		if(p.getCounts() < 3){
			return D2;
		}
		return D3orMore;
	}
	
	public void initialize(PhraseTable phraseTable){
		if(!phraseTable.countNormalized){
			phraseTable.normalizeCounts();
		}
		double n1 = phraseTable._numPhrasesWithCounts[1];
		double n2 = phraseTable._numPhrasesWithCounts[2];
		double n3 = phraseTable._numPhrasesWithCounts[3];
		double n4 = phraseTable._numPhrasesWithCounts[4];
		Y = n1 / (n1 + (double)2 * n2);
		D1 = (double)1 - (double)2 * Y * n2 / n1;
		D2 = (double)2 - (double)3 * Y * n3 / n2;
		D3orMore = (double)3 - (double)4 * Y * n4 / n3;
		initialized = true;
		System.out.println(n1+" "+n2+" "+n3+" "+n4);
		System.out.println("Modified Kneser-Ney Smoothing Discounts are: Y = " + Y + " D1 = " + D1 + " D2 = " + D2 + " D3+ = " + D3orMore);
	}

}
